package cn.lili.modules.order.cart.render.impl;

import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SpringContextUtil;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.client.DistributionGoodsClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.entity.dos.DistributionGoods;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.order.cart.entity.dto.TradeDTO;
import cn.lili.modules.order.cart.entity.enums.RenderStepEnums;
import cn.lili.modules.order.cart.entity.vo.CartSkuVO;
import cn.lili.modules.order.cart.entity.vo.CartVO;
import cn.lili.modules.order.cart.render.CartRenderStep;
import cn.lili.modules.system.client.SettingClient;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.DistributionSetting;
import cn.lili.modules.system.entity.dto.WindowSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.seata.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class DistributionPriceFinalRender implements CartRenderStep {
    /**
     * 缓存
     */
    private final Cache cache;

    private final SettingClient settingClient;

    private final DistributionGoodsClient distributionGoodsClient;

    private final DistributionClient distributionClient;

    @Override
    public RenderStepEnums step() {
        return RenderStepEnums.DISTRIBUTIONFINAL;
    }

    @Override
    public void render(TradeDTO tradeDTO) {

        log.info("分销开始计算:{}", tradeDTO.getDistributionId());

        //如果存在分销员
        Distribution distribution = (Distribution) cache.get(CachePrefix.DISTRIBUTION.getPrefix() + tradeDTO.getDistributionId());
        if(distribution == null) {
            if(StringUtils.isNotEmpty(tradeDTO.getDistributionId())){
                distribution = distributionClient.getDistributionById(tradeDTO.getDistributionId());
            }
            if(distribution != null) {
                Setting setting = settingClient.get(SettingEnum.DISTRIBUTION_SETTING.name());
                DistributionSetting distributionSetting = JSONUtil.toBean(setting.getSettingValue(), DistributionSetting.class);
                cache.put(CachePrefix.DISTRIBUTION.getPrefix() + UserContext.getCurrentUser().getId(), distribution, distributionSetting.getDistributionDay().longValue(), TimeUnit.DAYS);
            }
        }
        log.info("====distribution====:{}", distribution);
        if (distribution == null) {
            return;
        }
        //循环订单商品列表，如果是分销商品则计算商品佣金
        tradeDTO.setDistributionId(distribution.getMemberId());
        tradeDTO.setDistributionName(distribution.getMemberName());

        List<String> skuIds = tradeDTO.getCheckedSkuList().stream().map(cartSkuVO -> cartSkuVO.getGoodsSku().getId()).toList();
        //是否包含分销商品
        List<DistributionGoods> distributionGoods = distributionGoodsClient.distributionGoods(skuIds);
        if (distributionGoods != null && !distributionGoods.isEmpty()) {
            distributionGoods.forEach(dg -> tradeDTO.getCartList().forEach(cartVO -> {
                cartVO.getSkuList().forEach(cartSkuVO -> {
                    if (cartSkuVO.getGoodsSku().getId().equals(dg.getSkuId())) {
                        cartSkuVO.setDistributionGoods(dg);
                    }
                });
            }));
        }

        SettingClient settingClient = SpringContextUtil.getBean(SettingClient.class);
//        Setting settingGreenGoods = settingClient.get(SettingEnum.GREEN_GOODS.name());
//        Setting settingNotGreenGoods = settingClient.get(SettingEnum.NOT_GREEN_GOODS.name());
        Setting setting = settingClient.get(SettingEnum.WINDOW_SHOW.name());
        WindowSetting windowSetting = JSONUtil.toBean(setting.getSettingValue(), WindowSetting.class);

        log.info("分销开始计算... == {}", JSONObject.toJSONString(windowSetting));
        for (CartVO cartVO : tradeDTO.getCartList()) {
            cartVO.getSkuList().forEach((cartSkuVO) -> {
                if (cartSkuVO.getDistributionGoods() != null) {
                    double rate = windowSetting != null && StringUtils.isNotEmpty(windowSetting.getWindows()) ? Double.parseDouble(windowSetting.getWindows()) / 100 : 0.0;
//                    Double rate = 0.0;
//                    if(cartSkuVO.getIsGreenGoods()) {
//                        rate = CurrencyUtil.div(JSONObject.parseObject(settingGreenGoods.getSettingValue()).getDoubleValue("distributionProportion"), 100);
//                    }else {
//                        rate = CurrencyUtil.div(JSONObject.parseObject(settingNotGreenGoods.getSettingValue()).getDoubleValue("distributionProportion"), 100);
//                    }

                    log.info("分销数据打印,num:{}, greenScore:{}, fMoney:{}, rate:{}",
                            cartSkuVO.getNum(), cartSkuVO.getPriceDetailDTO().getGreenScore(), cartSkuVO.getPriceDetailDTO().getFmoney(), rate);
                    log.info("分销数据打印,num:{}, greenScore:{}, fMoney:{}, rate:{}",
                            cartSkuVO.getNum(), cartSkuVO.getPriceDetailDTO().getGreenScore(), cartSkuVO.getPriceDetailDTO().getFmoney(), rate);
                    log.info("计算分销佣金：{}", cartSkuVO.getNum() * ((cartSkuVO.getPriceDetailDTO().getGreenScore() - (cartSkuVO.getPriceDetailDTO().getFmoney() / 10)) * rate));
                    // 减去F分抵扣再进行分佣
                    cartSkuVO.getPriceDetailDTO().setDistributorSettlementPrice(CurrencyUtil.mul(cartSkuVO.getNum(),
                            CurrencyUtil.mul(CurrencyUtil.sub(cartSkuVO.getPriceDetailDTO().getGreenScore()
                                    , CurrencyUtil.div(cartSkuVO.getPriceDetailDTO().getFmoney(), 10)), rate)));
                    log.info("####分销结算佣金#####{}", cartSkuVO.getPriceDetailDTO().getDistributorSettlementPrice());
                }
            });
        }

        tradeDTO.getCartList().forEach(cartVO -> {
            cartVO.getSkuList().forEach(cartSkuVO -> {
                cartVO.getPriceDetailDTO().setDistributorSettlementPrice(cartSkuVO.getPriceDetailDTO().getDistributorSettlementPrice());
            });
        });

        tradeDTO.getCartList().forEach(cartVO -> {
            tradeDTO.getPriceDetailDTO().setDistributorSettlementPrice(cartVO.getPriceDetailDTO().getDistributorSettlementPrice());
        });
    }
}
